﻿@page "/Account/ResendEmailConfirmation"

@using System.ComponentModel.DataAnnotations
@using System.Text
@using System.Text.Encodings.Web
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.Identity.UI.Services
@using Microsoft.AspNetCore.WebUtilities
@using MyApp.Data
@using MyApp.Identity

@inject UserManager<ApplicationUser> UserManager
@inject IEmailSender EmailSender
@inject NavigationManager NavigationManager
@inject IdentityRedirectManager RedirectManager

<PageTitle>Resend email confirmation</PageTitle>

<div class="mt-8 mx-auto max-w-lg">
    <Heading1>Resend email confirmation</Heading1>
    <Heading3>Enter your email.</Heading3>

    <StatusMessage class="mb-3" Message="@_message" />
    <EditForm Model="Input" FormName="resend-email-confirmation" OnValidSubmit="OnValidSubmitAsync" method="post">
        <DataAnnotationsValidator />
        <ValidationSummary class="mb-3 text-danger text-center font-semibold" />
        <div class="flex flex-col gap-y-4">
            <div>
                <label for="email" class="@TextInput.LabelClasses">Email</label>
                <div class="mt-1 relative rounded-md shadow-sm">
                    <InputText id="email" type="text" @bind-Value="Input.Email" class="@TextInput.InputClasses" aria-required="true" placeholder="name@example.com" />
                </div>
                <ValidationMessage For="() => Input.Email" class="mt-2 text-danger text-sm" />
            </div>
            <div>
                <PrimaryButton type="submit">Resend</PrimaryButton>
            </div>
        </div>
    </EditForm>
</div>

@code {
    private string? _message;

    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = default!;

    protected override void OnInitialized()
    {
        Input ??= new();
    }

    private async Task OnValidSubmitAsync()
    {
        var user = await UserManager.FindByEmailAsync(Input.Email!);
        if (user is null)
        {
            _message = "Verification email sent. Please check your email.";
            return;
        }

        var userId = await UserManager.GetUserIdAsync(user);
        var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
        var callbackUrl = NavigationManager.GetUriWithQueryParameters(
            $"{NavigationManager.BaseUri}Account/ConfirmEmail",
            new Dictionary<string, object?> { ["userId"] = userId, ["code"] = code });
        await EmailSender.SendEmailAsync(
            Input.Email!,
            "Confirm your email",
            $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

        _message = "Verification email sent. Please check your email.";
    }

    private sealed class InputModel
    {
        [Required]
        [EmailAddress]
        public string? Email { get; set; }
    }
}
